import React from 'react'
import { Spin, Divider, Row, Col, Select, Input, DatePicker} from 'antd'
const {MonthPicker} = DatePicker;
import Condition from 'components/condition'
const { If, Else } = Condition;
const InputGroup = Input.Group;
const Option = Select.Option;
import Charts from 'components/echarts'
import moment from "moment/moment";
import dashboardService from "containers/dashboard/dashboard.service";
import {messages} from "share/common";

import NullCard from "containers/dashboard/dashboard-component/null-card"
import CardTitle from "containers/dashboard/dashboard-component/card-title"

class Report extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      load: false,
      hasGetData: false,
      amountList: [],
      paidTotalAmount: 0,
      payingTotalAmount: 0,
      monthlyExpenseOverviewList: [],
      options: {}
    };
    this.options = {};
  }

  componentDidMount() {
    this.getChartData("5");
  }

  getChartData = (key) => {
    const {hasGetData} = this.state;
    this.setState({load: true});
    let date = typeof key === "string" ? moment() : key;
    if (date) {
      dashboardService.getPersonalReportOverview(date.year(), date.month() + 1).then(res => {
        let paidAmountList = [];
        let payingAmountList = [];
        let xAxis = [];
        let baseCurrencyCode = res.data.baseCurrencyCode;
        res.data.paidAmountList.map(item => paidAmountList.push(item.totalAmount));
        res.data.payingAmountList.map(item => payingAmountList.push(item.totalAmount));
        res.data.amountList.map(item => xAxis.push(moment().month(item.month -1).format("MMM")));

        let monthlyExpenseOverviewList = res.data.monthlyExpenseOverviewList.length > 3 ?
          res.data.monthlyExpenseOverviewList.sort((a,b) => a.totalAmount - b.totalAmount).slice(0,3)
          :
          res.data.monthlyExpenseOverviewList;
        this.setState({
          amountList: res.data.amountList,
          load: false,
          xAxis,
          paidTotalAmount: res.data.paidTotalAmount.totalAmount,
          payingTotalAmount: res.data.payingTotalAmount.totalAmount,
          monthlyExpenseOverviewList,
          currentMonth: date
        }, () => {
          const options = {
            title: {
              show: true,
              text: messages('dashboard.key31'/*已报销金额*/),
              textStyle: {
                color: "rgba(0,0,0,0.85)",
                fontSize: 14,
              }
            },
            color: ['#3AA0FF','#0259B0'],
            tooltip : {
              trigger: 'axis',
              axisPointer : {
                type : 'shadow'
              },
              padding: [6,28,0,12],
              backgroundColor: 'rgba(0,0,0,0.75)',
              textStyle: {
                fontWeight: "normal",
                fontSize: 14
              },
              extraCssText: 'box-shadow: 0 2px 8px 0;border-radius: 4px;height: 90px',
              formatter: function(params){
                let result = '';
                let total = 0;
                let name = '';
                params.forEach(function (item) {
                  total += item.value;
                  name = item.name;
                  result += `<span style="display:inline-block;margin-right:8px;width:6px;height:6px;background-color:${item.color}"></span>${item.seriesName}：${React.Component.prototype.filterMoney(item.value,2,true)}<br/>`;
                });
                return `${name}，${baseCurrencyCode} ${React.Component.prototype.filterMoney(total,2,true)}<br/>${result}`
              }
            },
            legend: {
              left: 100,
              itemWidth: 8,
              itemHeight: 8,
              textStyle:{
                color: "rgba(0,0,0,0.65)",
                fontSize: 12
              },
              data: [{
                name: messages('dashboard.key32')/*已付款*/,
                icon: 'square'
              },{
                name: messages('dashboard.key33')/*未付款*/,
                icon: 'square'
              }]
            },
            grid: {
              top: 40,
              left: '3%',
              right: '4%',
              bottom: 20,
              containLabel: true
            },
            yAxis:  {
              type: 'value',
              splitLine: {
                lineStyle:{
                  type: "dashed"
                }
              }
            },
            xAxis: {
              type: 'category',
              data: xAxis,
              boundaryGap: true,
              axisTick: {
                alignWithLabel: true
              },
            },
            series: [
              {
                name: messages('dashboard.key32')/*已付款*/,
                type: 'bar',
                stack: '总量',
                data: paidAmountList
              },
              {
                name: messages('dashboard.key33')/*未付款*/,
                type: 'bar',
                stack: '总量',
                data: payingAmountList,
                barWidth: 24
              }
            ]
          };
          this.setState({options})
        });
      })
    }else{
      this.setState({
        amountList: []
      });
    }
  };

  render() {
    const {load, amountList, currentMonth, paidTotalAmount, payingTotalAmount, monthlyExpenseOverviewList, options} = this.state;
    const {removeModule } = this.props;

    return (
      <Spin spinning={load}>
        <CardTitle  cardKey={"5"}
                    title={messages('dashboard.key29'/*报表*/)}
                    removeModule={(key) => removeModule(key)}
                    reloadModule={() => this.getChartData("5")}>
          <InputGroup compact className="card-input">
            <Select defaultValue="Option1">
              <Option value="Option1">{messages('dashboard.key162')/*提报日期*/}</Option>
            </Select>
            <MonthPicker
              disabledDate={current => current && (current.valueOf() > Date.now() || current.valueOf() < Date.now() - 31536000000)}
              style={{width: '100%'}}
              onChange={this.getChartData}
              allowClear={false}
              value={currentMonth}
              defaultValue={moment()}/>
          </InputGroup>
        </CardTitle>
        <div className="card-content">
          {
            amountList.length ? (
              <div>
                <Row>
                  <Col span={16}>
                    <Charts options={options} height={240}/>
                  </Col>
                  <Col span={8} style={{paddingLeft: 40}}>
                    <div className="amount-area">
                      <div className="paid-amount paid-title">
                        {messages('dashboard.key31'/*已报销金额*/)}
                        <div className="amount">{this.filterMoney(paidTotalAmount + payingTotalAmount)}</div>
                      </div>
                      <div className="paid-amount">
                        <span className="paid-dot default-color-bg" />
                        {messages('dashboard.key32'/*已付款*/)}
                        <div className="amount">{this.filterMoney(paidTotalAmount)}</div>
                      </div>
                      <div className="paid-amount">
                        <span className="paid-dot default-color-focus-bg" />
                        {messages('dashboard.key33'/*未付款*/)}
                        <div className="amount">{this.filterMoney(payingTotalAmount)}</div>
                      </div>
                    </div>
                    <div className="expense-rank">
                      <div className="paid-amount paid-title"> {messages('dashboard.key163')/*费用类型TOP3*/}
                      </div>
                      <Condition>
                        <If value={monthlyExpenseOverviewList.length}>
                          {monthlyExpenseOverviewList.map((item, index) => {
                            return (
                              <div className="paid-amount" key={index}>
                                <img src={item.iconUrl} width={12.8} height={12.8}/>
                                {item.expenseTypeName}
                                <div className="amount">{this.filterMoney(item.totalAmount)}</div>
                              </div>
                            )
                          })}
                        </If>
                        <Else>
                          <Divider dashed style={{margin: "12px 0"}}/>
                          <p className='font-disabled' style={{textAlign: "center"}}>{messages('dashboard.key164')/*没有更多啦*/}</p>
                        </Else>
                      </Condition>
                    </div>
                  </Col>
                </Row>
              </div>
            ) : (
              <NullCard imgType={"report"} message={messages('dashboard.key129')/*还没有报表数据*/}/>
            )
          }
        </div>
      </Spin>
    )
  }
}

Report.propTypes = {
  removeModule: React.PropTypes.func.isRequired,
};

Report.defaultProps={
};

export default Report
